/**
 * mysql工具 文件
 *
 */
import mysql, { MysqlError, PoolConnection } from "mysql";
import { DATABASE } from "../config/db.config";

const pool = mysql.createPool({
  host: DATABASE.HOST,
  user: DATABASE.USER,
  password: DATABASE.PASSWORD,
  database: DATABASE.DATABASE,
  connectionLimit: DATABASE.CONNECTION_LIMIT,
});

// 数据库查询方法
export const dbQuery = (sql: string, values: unknown[] = []):Promise<{[key:string]:unknown}[]> => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err: MysqlError, connection: PoolConnection) => {
      if (err) {
        return reject(err);
      } else {
        connection.query(sql, values, (err, rows) => {
          connection.release();
          if (err) {
            return reject(err);
          } else {
            return resolve(rows);
          }
        });
      }
    });
  });
};
